<?php

namespace app\model\oa;

use think\Model;
use think\model\concern\SoftDelete;

/**
 * 车辆维修记录模型
 * @package app\model\oa
 */
class CarRepair extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'car_repair';

    // 主键
    protected $pk = 'id';

    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'car_id' => 'integer',
        'types' => 'integer',
        'repair_time' => 'datetime',
        'amount' => 'float',
        'handled' => 'integer',
        'admin_id' => 'integer',
        'create_time' => 'int',
        'update_time' => 'int',
        'delete_time' => 'int',
    ];

    // 维修类型常量
    const TYPE_REPAIR = 1;      // 维修
    const TYPE_MAINTENANCE = 2; // 保养

    /**
     * 获取类型文本
     */
    public static function getTypeText($type)
    {
        $texts = [
            self::TYPE_REPAIR => '维修',
            self::TYPE_MAINTENANCE => '保养',
        ];
        return $texts[$type] ?? '未知';
    }

    /**
     * 关联车辆
     */
    public function car()
    {
        return $this->belongsTo('app\model\oa\Car', 'car_id', 'id');
    }

    /**
     * 关联经手人
     */
    public function handler()
    {
        return $this->belongsTo('app\model\admin\User', 'handled', 'id');
    }

    /**
     * 关联管理员
     */
    public function admin()
    {
        return $this->belongsTo('app\model\admin\User', 'admin_id', 'id');
    }

    /**
     * 获取维修记录列表
     */
    public static function getList($params = [])
    {
        $query = self::with(['car', 'handler', 'admin'])
            ->where('types', self::TYPE_REPAIR)
            ->order('create_time', 'desc');

        // 按车辆筛选
        if (!empty($params['car_id'])) {
            $query->where('car_id', $params['car_id']);
        }

        // 按时间范围筛选
        if (!empty($params['start_time']) && !empty($params['end_time'])) {
            $startTime = strtotime($params['start_time']);
            $endTime = strtotime($params['end_time']) + 86399;
            $query->whereBetween('repair_time', [$startTime, $endTime]);
        }

        // 关键词搜索
        if (!empty($params['keywords'])) {
            $query->where(function ($query) use ($params) {
                $query->whereLike('content', '%' . $params['keywords'] . '%')
                    ->whereOr('address', 'like', '%' . $params['keywords'] . '%');
            });
        }

        return $query->paginate($params['limit'] ?? 15);
    }
}